// 注：先看readme.md文件
// 对联生成请求
const cloud = require('wx-server-sdk')
var rp = require('request-promise')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const DB = cloud.database()
// 天行数据的KEY
var TIAN_XING_KEY = ''
// 天行数据的接口API
var TIAN_XING_API = 'http://api.tianapi.com/duilian/index'
// 百度Token
var BAI_DU_ACCESS_TOKEN = '' // 这里需要自行去申请咯~
// 百度接口api
var BAI_DU_API = [
  "https://aip.baidubce.com/rpc/2.0/creation/v1/poem", // 智能写诗
  "https://aip.baidubce.com/rpc/2.0/creation/v1/couplets" // 智能写对联
]


// 云函数入口函数
exports.main = async (event, context) => {
  var { action, text } = event
  var data = {}
  switch (action) {
    case 'getPoemByTxt': {
      data.text = text
      if (text == "")
        return {
          message: '缺少参数text'
        }
      // 智能写诗（API接口来源，参考百度-语言处理技术-智能创作平台-智能写诗：https://ai.baidu.com/ai-doc/NLP/ak53wc3o3）
      return new Promise((resolve, reject) => {
        try {
          rp({
            method: 'POST',
            headers: {
              "content-type": "application/json",
            },
            body: JSON.stringify(data),
            url: BAI_DU_API[0] + '?access_token=' + BAI_DU_ACCESS_TOKEN, // text必要参数，写诗的主题内容
          }, function (error, response, body) {
            if (error) {
              return reject(error);
            }
            return resolve(JSON.parse(body));
          })
        } catch (e) {
          return reject(e)
        }
      });
    }
    case 'getCoupletByTxt': {
      data.text = text
      if (text == "")
        return {
          message: '缺少参数text'
        }
      // 智能写对联（API接口来源，参考百度-语言处理技术-智能创作平台-智能写对联：https://ai.baidu.com/ai-doc/NLP/Ok53wb6dh）
      return new Promise((resolve, reject) => {
        try {
          rp({
            method: 'POST',
            headers: {
              "content-type": "application/json",
            },
            body: JSON.stringify(data),
            url: BAI_DU_API[1] + '?access_token=' + BAI_DU_ACCESS_TOKEN,  // text必要参数，对联的主题内容
          }, function (error, response, body) {
            if (error) {
              return reject(error);
            }
            return resolve(JSON.parse(body));
          })
        } catch (e) {
          return reject(e)
        }
      });
    }
    case 'getRandomCouplet': {
      // 随机一对对联（无横批）（API接口来源，天行数据：https://www.tianapi.com/console/）
      return new Promise((resolve, reject) => {
        rp({
          url: TIAN_XING_API + '?key=' + TIAN_XING_KEY,
          method: "POST",
          json: true,
        }, function (error, response, body) {
          console.log("响应" + body)
          resolve(body)
          if (!error && response.statusCode == 200) {
            try { } catch (e) {
              reject()
            }
          }
        })
      })
    }
    default: {
      return {
        message: 'action错误！'
      }
    }
  }

}